#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>


int tcp_connect(const char *hostname, const char *service)
{
    int sockfd, n;

    struct addrinfo hints, *res, *resave;

    bzero(&hints, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if ((n = getaddrinfo(hostname, service, &hints, &res)) != 0) {
        fprintf(stderr, "tcp_connect error for %s, %s: %s\n", hostname, service, gai_strerror(n));
        exit(1);
    }
    resave = res;
    
    do {
        sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
        if (sockfd < 0)
            continue;

        if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0)
            break;   /* success connect to server */

        if (close(sockfd) < 0) {
            perror("close error");
        }
    }while ((res = res->ai_next) != NULL);

    if (res == NULL) {
        fprintf(stderr, "tcp_connect error for %s, %s\n", hostname, service);
    }

    freeaddrinfo(resave);

    return sockfd;
}
